import { Form, Input, Button, message } from 'antd';
import React from 'react'
import { login } from '../../api'
import { useHistory } from 'react-router-dom'

const Demo = () => {
  const history = useHistory()
  // 点击登录 验证通过才会触发的函数
  const onFinish = async (values) => {
    // 请求登录接口 
    // value 数据  格式 { username: String, password: String }
    const resp = await login(values)

    const { code } = resp.data 
    // 判断状态吗
    if(code === 200) {
      message.success('登录成功， 2s之后自动跳转首页...')

      setTimeout(() => {
        history.push({ pathname: '/home/index' })
      }, 2000)
    } else {
      message.error('账户密码错误， 请重修输入！')
    }
    
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div style={{ width: 800, position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)' }}>
      <Form
        name="basic"
        labelCol={{
          span: 4,
        }}
        wrapperCol={{
          span: 20,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="账户"
          name="username"
          rules={[
            {
              required: true,
              message: 'Please input your username!',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true,
              message: 'Please input your password!',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>


        <Form.Item
          wrapperCol={{
            offset: 4,
            span: 20,
          }}
        >
          <Button type="primary" htmlType="submit" style={{ width: '100%' }}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};



export default Demo